package com.java2007.controller.backend;
import com.java2007.controller.BaseServlet;
import com.java2007.factory.BeanFactory;
import com.java2007.pojo.Admin;
import com.java2007.service.AdminService;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * @author ZOU
 */
@WebServlet("/admin")
public class AdminController extends BaseServlet {
    private AdminService adminService= (AdminService) BeanFactory.getBean("com.java2007.service.impl.AdminServiceImpl");

    /**
     * 登录
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String adminName = request.getParameter("adminName");
        String password = request.getParameter("password");

        Admin admin = adminService.login(adminName, password);
        if (admin == null){
            request.setAttribute("error","用户名或密码错误，请重新输入");
            return "forward:/index.jsp";
        }else {
            request.getSession().setAttribute("admin",admin);
            Integer role = admin.getRole();
            //判断其是普通用户还是管理员
            if (role >= 2){
                return "redirect:/front?method=findAll";
            }
             return "redirect:"+request.getContextPath()+"/backend/index.jsp";
        }
    }

    /**
     * 后台登录状态
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String topLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        request.getSession().setAttribute("username",username);
        return "redirect:/backend/index.jsp";
    }

    /**
     * 退出
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        session.removeAttribute("admin");
        return "redirect:/index.jsp";
    }

}
